<template>
	<view class="offerToBuy">
		<view class="main">
					<view class="buyPoup">
						<view class="header">
								<view class="reciveInfo" @click="addrList">
										<view class="info_text" v-if="addressList.length>0">
											<view class="info_name">
												<text class="name">{{name}}</text><text class="mobile">{{mobile}}</text>
											</view>
											<text class="address">{{addr}}</text>
										</view>
										<view class="info_text noAddress" v-if="noAddress" >
											<i class='iconfont'>&#xe662;</i>
											<text>添加地址(用于邮寄合同，请正确选择)</text>
										</view>
										<view class="icon">
											<uni-icon type="arrowright" size="20"></uni-icon>
										</view>	
								</view>
								<view class="imageWrap">
									<image src="../../static/image/line_address.png" mode="widthFix"></image>
								</view>
						</view>
						
						<view class="buy_num">
							<view class="title" >
								<text>购买数量</text> <text class="gray" v-if='userLimit >0'> (每人限购{{userLimit}}份)</text>
							</view>
							<view class="num">
								<uni-number-box :min="1" :max="numMax" v-model='inputValue' v-on:change="onNumberChange"></uni-number-box>
							</view>
							
						</view>
						<!-- <view class="buy_num referrer" v-if="code ==''"> -->
							<!-- <view class="title"> -->
								<!-- <text>推荐人:</text> -->
							<!-- </view> -->
							<!-- <input class="uni-input" type="number" :value='referrerCode' placeholder="请输入推荐人ID" /> -->
							<!-- <input :adjust-position='adjustPosition' class="uni-input" type="number" v-model='referrerCode' placeholder="请输入推荐人ID" placeholder-style="color:#cccccc"/> -->
								
						<!-- </view> -->
						<view class="payType_title">
							<text>支付方式</text> <text class="gray">(大额订单请到个人中心充值)</text>
						</view>
						<view class="payType">
				
							
								<radio-group @change="radioChange" class="radioGroup" v-if="deposit>0">
												
													<label class="radio">
															<view class="leftType">
																<view class="iconWrap e_wallet">
																	<i class='iconfont'>&#xe61e;</i>
																</view>
																<text>在线支付</text>
																<text class='gray'>(电子钱包可抵{{surplus}}元）</text>
															</view>
															<radio value="online" :checked='checked' color="#ff1268"/>
													</label>
													
													
													<label class="radio">
															<view class="leftType">
																<view class="iconWrap offline">
																	<i class='iconfont'>&#xe61d;</i>
																</view>
																<view class="right">
																	<text>线下支付</text>
																	<text class='gray'>({{deposit}}元定金，{{tailConfirmTime}}内线下支付尾款）</text>
																</view>
																
															</view>
															<radio value="offline"  color="#ff1268"/>
													</label>
													
								</radio-group>
								<radio-group @change="radioChange" class="radioGroup" v-if="deposit===0">
												
													<label class="radio">
															<view class="leftType">
																<view class="iconWrap Alipay">
																	<i class='iconfont'>&#xe702;</i>
																</view>
																<text>支付宝</text>
																<text class='gray'>(电子钱包可抵{{surplus}}元）</text>
															</view>
															<radio value="alipay" checked color="#ff1268"/>
													</label>
													<label class="radio">
															<view class="leftType">
																<view class="iconWrap wachat">
																	<i class='iconfont'>&#xe605;</i>
																</view>
																<text>微信支付</text>
																<text class='gray'>(电子钱包可抵{{surplus}}元）</text>
															</view>
															<radio value="wachat"  color="#ff1268"/>
													</label>
								</radio-group>
						</view>
						<view class="agree">
									<checkbox color="#ff1268" v-bind:checked='checkboxChecked' @click="checkboxChecked = !checkboxChecked"/>我已仔细阅读并同意<text class="red" @click="agreement">《视纪影视平台服务协议》</text>
								
						</view>
						
					</view>
		</view>
			
			<view class="footerFixed">
				
				<view class="left">
					<view>合计金额 :</view>
					<view class="price">￥{{orderMoney}}</view>
				</view>
				<view class="buyBtn order" @click="show_payPoup" hover-class="show_buyPoup_hover">提交订单
				</view>
				
			</view>
		
		
		
		
		
		
		<!--支付 -->
		
		<uni-popup :show="payPoup" :type="pay_Type" v-on:hidePopup="hidePopup">
			<view class="pay_Poup">
				<i class='iconfont close' @click='hidePopup'>&#xe8b6;</i>
				<view class="pay_PoupWrap">
					<view class="line1" v-if="'offline' != payType">
						订单金额：<text>￥{{orderMoney }}</text>
					</view>
					<view class="line1" v-if="'offline' == payType">
						预付定金：<text>￥{{deposit}}</text>
					</view>
					<view class="line2">
						<view>
							钱包余额：<text>￥{{surplus}}</text>
						</view>
						<view class="icon">
							<radio value="" :checked='isPacket' @click='clickPacket' color="#FF1268"/>
						</view>
					</view>
					<view class="middle">
						<text class="mid-title">还需支付</text>
						<view><text>{{spareMoney}}</text><text>元</text></view>
					</view>
					
					<view v-if='deposit>0'>
							<view class="choosePayType"  v-if='spareMoney>0'>
									<view class="btn wachat" @click="wachatPay">
										<i class='iconfont'>&#xe605;</i>
										<text>微信</text>
								</view>
								<view class="btn Alipay" @click="Alipay">
										<i class='iconfont'>&#xe702;</i>
										<text>支付宝</text>
								</view>
							</view>
							<view class="confirm btn" v-if='spareMoney == 0' @click="userPay">
								确定支付
							</view>
								
					</view>
					<view v-if='deposit===0'>
								<view class="btn wachat" @click="wachatPay" v-if="payType ==='wachat' &&spareMoney>0">
									<i class='iconfont'>&#xe605;</i>
									<text>微信</text>
							</view>
							<view class="btn Alipay" @click="Alipay" v-if="payType ==='alipay' &&spareMoney>0">
									<i class='iconfont'>&#xe702;</i>
									<text>支付宝</text>
							</view>
							<view class="confirm btn" v-if='spareMoney == 0' @click="userPay">
								确定支付
							</view>
					</view>
				</view>
			</view>
		</uni-popup>
		
		
	</view>
</template>

<script>
import uniIcon from '@/components/uni-icon.vue';
import uniPopup from '@/components/uni-popup.vue';
import uniNumberBox from '@/components/uni-number-box';
var util = require('../../common/util.js');
export default {
    data() {
        return {
            addressList: [],
            bannerSrc: '',
            tailConfirmTime: '',
            payType: 'online',
            numMax: 0,
            inviteCode: '',
            surplus: 0,
            deposit: 0, //定金
            spareMoney: 0, //还需付款
            orderMoney: 0, //订单金额
            // offLineSpareMoney: 0, //线下还需付款
            scale: 0,
            percent: 0,
            surplusNum: 0,
            userLimit: 0,
            title: '',
            type: '',
            status: '',
            incomeDetail: '',
            content: '',
            checkboxChecked: true,
            share_Poup: false,
            offlinePayPoup: false,
            noAddress: false,
            payPoup: false,
            isPacket: true,
            tip_Poup: false,
            checked: true,
            popType: 'bottom',
            pay_Type: 'middle',
            price: 0,
            movieId: 0,
            showPopup: false,
            adjustPosition: false,
            name: '',
            mobile: '',
            authTime: '',
            authStatusValue: '',
            isReferrerId: false,
            addr: '',
            // addr: '四川省  成都市  武侯区  成都花园栋2单元2号',
            inputValue: 1,
            params: {
                orderId: 0,
                number: 0,
                orderType: 'movie',
                unionId: '',
                payType: 'alipay',
                surplus: 0,
                offlinePay: false,
                remark: '',
                name: '',
                mobile: '',
                address: '',
                inviteCode: '',
                token: util.getUserToken()
            }
        };
    },
    onShow(e) {
        this.getAddressList();
    },

    onLoad: function(option) {
        //option为object类型，会序列化上个页面传递的参数
        // console.log(option.price); //打印出上个页面传递的参数
        // console.log(option.movieId);
        this.globalRuleGet();
        this.movieId = option.movieId;
        this.surplusNum = parseInt(option.surplusNum);
        this.userLimit = parseInt(option.userLimit);
        if (option.buyNum) {
            this.inputValue = parseInt(option.buyNum);
        }
        if (this.userLimit > 0) {
            this.numMax = this.userLimit > this.surplusNum ? this.surplusNum : this.userLimit;
        } else {
            this.numMax = this.surplusNum;
        }

        //         console.log(this.userLimit);
        console.log(this.numMax);
        this.deposit = parseFloat(option.deposit);
        // console.log(this.deposit)
        this.price = parseFloat(option.price);
        if (this.deposit > 0) {
            this.payType = 'online';
        } else {
            this.payType = 'alipay';
        }
        this.orderMoney = (this.inputValue * this.price).toFixed(2);

        this.getUserInfo();
        this.getAddressList();
    },

    methods: {
        globalRuleGet() {
            util.ajax(
                'globalRuleGet',
                {
                    token: util.getUserToken()
                },
                data => {
                    let json = data.data;
                    if (json.status) {
                        // console.log(json.data.rule.tailConfirmHour);
                        let tailConfirmHour = json.data.rule.tailConfirmHour;
                        // console.log(tailConfirmHour)
                        if (+tailConfirmHour > 60) {
                            this.tailConfirmTime =
                                +tailConfirmHour % 60 != 0
                                    ? parseInt(+tailConfirmHour / 60) +
                                      '小时' +
                                      (tailConfirmHour % 60) +
                                      '分钟'
                                    : parseInt(+tailConfirmHour / 60) + '小时';
                        } else {
                            this.tailConfirmTime = tailConfirmHour + '分钟';
                        }
                        // console.log(this.tailConfirmTime);
                    } else {
                        uni.showToast({
                            title: json.message,
                            icon: 'none',
                            duration: 1000
                        });
                    }
                },
                (data, code) => {
                    console.log(data);
                    uni.showToast({
                        title: JSON.stringify(data.message),
                        icon: 'none',
                        duration: 1000
                    });
                }
            );
        },
        agreement() {
            uni.navigateTo({
                url: '../my/tool/userAgreement'
            });
        },
        getAddressList() {
            util.ajax(
                'userAddresses',
                {
                    token: util.getUserToken()
                },
                data => {
                    let json = data.data;
                    if (json.status) {
                        this.addressList = [];
                        // console.log(json.data);
                        if (json.data.length > 0) {
                            this.addressList = json.data;
                            if (uni.getStorageSync('receiveInfo')) {
                                let obj = uni.getStorageSync('receiveInfo');
                                this.name = obj.name;
                                this.addr = obj.detail;
                                this.mobile = obj.mobile;
                            } else {
                                this.name = json.data[0].name;
                                this.addr = json.data[0].detail;
                                this.mobile = json.data[0].mobile;
                            }
                        } else {
                            uni.removeStorageSync('receiveInfo');
                        }
                        if (this.addressList.length === 0) {
                            this.noAddress = true;
                        } else {
                            this.noAddress = false;
                        }
                    }
                },
                (data, code) => {
                    console.log(data);
                }
            );
        },
        clickPacket() {
            this.isPacket = !this.isPacket;
            // 				console.log(this.orderMoney)
            // 				console.log(this.surplus)
            this.isPacketType();
        },
        isPacketType() {
            let totalMoney = 0;
            if ('offline' != this.payType) {
                //线上支付
                totalMoney = this.orderMoney;
            } else {
                //线下支付
                totalMoney = this.deposit;
            }

            let surplus = 0;
            if (this.isPacket) {
                if (totalMoney < this.surplus) {
                    surplus = totalMoney;
                } else {
                    surplus = this.surplus;
                }
            }

            this.spareMoney = (totalMoney - surplus).toFixed(2);
            console.log(totalMoney, surplus, this.spareMoney);

            this.params.surplus = parseInt(surplus * 100);

            // this.pay();
        },
        getUserInfo() {
            util.ajax(
                'userDetail',
                {
                    token: util.getUserToken()
                },
                data => {
                    let json = data.data;
                    if (json.status) {
                        //                         this.authTime = json.data.authTime;
                        this.inviteCode = json.data.code;
                        //                         this.authStatusValue = json.data.authStatus.value;
                        this.surplus = util.showDecimal(json.data.surplus);
                        // console.log(this.code);
                    } else {
                        uni.showToast({
                            title: json.message,
                            icon: 'none',
                            duration: 1000
                        });
                    }
                },
                (data, code) => {
                    // console.log(data);
                    uni.showToast({
                        title: JSON.stringify(data.message),
                        icon: 'none',
                        duration: 1000
                    });
                }
            );
        },
        authStatus() {
            uni.showModal({
                title: '温馨提示',
                content:
                    '根据国家相关监管政策要求，购买理财产品需实名认证。请实名认证后再认购产品。',
                cancelText: '去认证',
                cancelColor: '#cccccc',
                confirmText: '再看看',
                confirmColor: '#fff',
                success: res => {
                    if (res.confirm) {
                    } else if (res.cancel) {
                        if (this.authStatusValue === 'checking') {
                            uni.navigateTo({
                                url: '../my/toCertification3'
                            });
                        } else {
                            uni.navigateTo({
                                url: '../my/toCertification'
                            });
                        }
                    }
                },
                fail: () => {},
                complete: () => {}
            });
        },

        show_payPoup() {
            // console.log(this.checkboxChecked);
            // console.log(this.addr);
            if (this.addressList.length === 0 || !this.addr) {
                uni.showToast({
                    title: '请添加邮寄地址',
                    icon: 'none',
                    duration: 1000
                });
                return;
            }
            if (this.inputValue === 0 || this.inputValue === '') {
                uni.showToast({
                    title: '请输入购买数量',
                    icon: 'none',
                    duration: 1000
                });
                return;
            }
            console.log(this.inputValue);
            if (this.inputValue > this.numMax) {
                uni.showToast({
                    title: '超出最大购买数，请重新输入',
                    icon: 'none',
                    duration: 1000
                });
                return;
            }

            if (!this.checkboxChecked) {
                uni.showToast({
                    title: '请同意平台服务协议',
                    icon: 'none',
                    duration: 1000
                });
                return;
            }

            this.isPacket = true;
            this.isPacketType();
            this.payPoup = true;
        },

        pay() {
            // this.payPoup = true;
            console.log(this.payType);
        },
        radioChange(e) {
            this.payType = e.target.value;
            console.log(this.payType);

            //             var changed = {};
            //             for (var i = 0; i < this.radioItems.length; i++) {
            //                 if (checked.indexOf(this.radioItems[i].name) !== -1) {
            //                     changed['radioItems[' + i + '].checked'] = true;
            //                 } else {
            //                     changed['radioItems[' + i + '].checked'] = false;
            //                 }
            //             }
        },
        hidePopup() {
            this.showPopup = false;
            this.share_Poup = false;
            this.payPoup = false;
            this.offlinePayPoup = false;
            // this.spareMoney = 0;
            this.isPacket = true;
        },
        cancle() {
            this.share_Poup = false;
        },
        addrList() {
            uni.navigateTo({
                url: './addrList'
            });
        },

        wachatPay() {
            this.params.payType = 'wxpay';
            this.userPay();
        },
        Alipay() {
            this.params.payType = 'alipay';
            this.userPay();
        },
        userPay() {
            this.params.unionId = this.movieId;
            this.params.number = this.inputValue;

            console.log(this.spareMoney);

            if (this.spareMoney == 0) {
                this.params.payType = 'surplus';
            }

            this.params.offlinePay = 'offline' == this.payType;
            this.params.name = this.name;
            this.params.mobile = this.mobile;
            this.params.address = this.addr;
            this.params.inviteCode = this.inviteCode;

            uni.showLoading({
                title: '加载中...',
                mask: false
            });
            util.ajax(
                'userPay',
                this.params,
                data => {
                    uni.hideLoading();
                    let json = data.data;
                    if (json.status) {
                        console.log(json);
                        this.params.orderId = json.orderId;
                        console.log(json.orderId);
                        console.log(json.data);
                        if ('surplus' == this.params.payType) {
                            if (this.params.offlinePay) {
                                uni.reLaunch({
                                    url: './preorderSuccess?id=' + json.orderId
                                });
                            } else {
                                uni.reLaunch({
                                    url: './buySuccess?id=' + json.orderId
                                });
                            }
                        } else {
                            uni.requestPayment({
                                provider: this.params.payType,
                                orderInfo: json.data, //订单数据
                                success: function(res) {
                                    console.log('success:' + JSON.stringify(res));
                                    if (this.params.offlinePay) {
                                        uni.reLaunch({
                                            url: './preorderSuccess?id=' + json.orderId
                                        });
                                    } else {
                                        uni.reLaunch({
                                            url: './buySuccess?id=' + json.orderId
                                        });
                                    }
                                },
                                fail: function(err) {
                                    console.log('fail:' + JSON.stringify(err));
                                }
                            });
                        }
                    } else {
                        uni.showToast({
                            title: json.message,
                            icon: 'none',
                            duration: 1000
                        });
                    }
                },
                (data, code) => {
                    console.log(data);
                    uni.showToast({
                        title: JSON.stringify(data.message),
                        icon: 'none',
                        duration: 1000
                    });
                }
            );
        },
        onNumberChange(value) {
            console.log(value, 'value');
            console.log(this.numMax, 'numMax');
            if (value > this.numMax) {
                uni.showToast({
                    title: '超出最大购买数，请重新输入',
                    icon: 'none',
                    duration: 1000
                });
            }
            // this.inputValue = this.numMax;

            this.inputValue = value;
            this.orderMoney = util.showDecimal(this.inputValue * this.price * 100);
        }
    },
    components: {
        uniIcon,
        uniPopup,
        uniNumberBox
    }
};
</script>
<style lang="less">
@import '../../common/icon.css';
@import '../../common/uni.css';
// page {
//     background: white;
// }
/*通用 */
view {
    font-size: 28upx;
    line-height: 1.15;
}
.offerToBuy {
    flex: 1;

    height: 100%;
    padding-bottom: 100upx;
    overflow: hidden;

    .main {
        flex-direction: column;
        width: 100%;
        padding: 30upx 20upx 0;
        box-sizing: border-box;
        .buyPoup {
            flex-direction: column;
            border-top-left-radius: 50upx;
            border-top-right-radius: 50upx;
            width: 100%;
            .header {
                background: white;
                height: 190upx;
                align-items: center;
                position: relative;
                box-shadow: 0 0 0.277778rem #e8e6e6;
                .imageWrap {
                    position: absolute;
                    left: 0;
                    bottom: 0;
                    height: 5upx;
                    width: 100%;
                    image {
                        width: 100%;
                        height: 100%;
                    }
                }
                .reciveInfo {
                    width: 100%;
                    padding: 20upx 16upx;
                    box-sizing: border-box;
                    justify-content: space-between;
                    .info_text {
                        flex-direction: column;
                        .info_name {
                            text {
                                font-size: 34upx;
                                color: #000000;
                                // font-weight: 600;
                            }
                            .name {
                                margin-right: 42upx;
                            }
                        }

                        .address {
                            margin-top: 20upx;
                            font-size: 26upx;
                            color: rgb(102, 102, 102);
                        }
                    }
                    .noAddress {
                        color: #ff1268;
                        flex-direction: row;
                        align-items: center;
                        text {
                            margin-left: 18upx;
                            font-size: 28upx;
                        }
                    }
                    .icon {
                        align-items: center;
                        color: #cccccc;
                    }
                }
            }
            .buy_num {
                justify-content: space-between;
                height: 100upx;
                align-items: center;
                padding: 0 16upx;
                box-sizing: border-box;
                background: white;
                margin-top: 20upx;
                .title {
                    align-items: center;
                    text:first-child {
                        font-size: 30upx;
                        color: #000000;
                        margin-right: 10upx;
                    }
                    .gray {
                        font-size: 24upx;
                        color: rgb(204, 204, 204);
                        justify-content: center;
                        align-items: center;
                    }
                }
                .num {
                }
            }
            .referrer {
                align-items: center;
                .uni-input {
                    align-items: center;
                }
            }
            .payType_title {
                margin-top: 20upx;
                padding: 30upx 16upx;
                background: white;
                display: block;
                text:first-child {
                    font-size: 30upx;
                    color: #000000;
                    margin-right: 10upx;
                }
                .gray {
                    font-size: 24upx;
                    color: rgb(153, 153, 153);
                }
            }
            .payType {
                background: white;
                padding: 0 16upx 30upx;
                .radioGroup {
                    width: 100%;
                    .radio:first-child {
                        border-bottom: 1upx solid #eeeeee;
                    }
                    .radio {
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                        align-items: center;
                        height: 100upx;

                        .leftType {
                            align-items: center;
                            .iconWrap {
                                background: #ff1268;
                                width: 70upx;
                                height: 70upx;
                                border-radius: 50%;
                                color: white;
                                align-items: center;
                                justify-content: center;
                                margin-right: 18upx;
                                .iconfont {
                                    font-size: 40upx;
                                }
                            }
                            .right {
                                display: block;
                            }
                            .gray {
                                flex-wrap: nowrap;
                                color: rgb(102, 102, 102);
                                font-size: 24upx;
                            }
                            .Alipay {
                                background: #1196da;
                            }
                            .wachat {
                                background: #29a415;
                            }
                            .offline {
                                background: #2e3245;
                            }
                        }
                    }
                }
            }
            .agree {
                margin-top: 20upx;
                width: 100%;
                height: 100upx;
                align-items: center;
                color: rgb(153, 153, 153);
                font-size: 24upx;
                display: block;
                .red {
                    color: #ff1268;
                }
			}
        }
    }
    .footerFixed {
        background: white;
        width: 100%;
        position: fixed;
        left: 0;
        bottom: 0;
        height: 110upx;
        box-shadow: 0 0 0.277778rem #e8e6e6;
        .left {
            padding-right: 30upx;
            width: 70%;
            box-sizing: border-box;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center;
            .price {
                font-size: 32upx;
                color: #ff1268;
                margin-left: 16upx;
            }
        }
        .order {
            width: 30%;
            justify-content: center;
            align-items: center;
            font-size: 32upx;
            background: -webkit-linear-gradient(to right, #ff48ac, #ff1268);
            background: -o-linear-gradient(to right, #ff48ac, #ff1268);
            background: -moz-linear-gradient(to right, #ff48ac, #ff1268);
            background: -mos-linear-gradient(to right, #ff48ac, #ff1268);
            background: linear-gradient(to right, #ff48ac, #ff1268);
            color: white;
        }
    }

    .pay_Poup {
        width: 100%;
        height: auto;
        background: transparent;
        position: relative;
        // left: 0;
        .close {
            position: absolute;
            top: -18upx;
            right: -2upx;
            color: #999999;
        }
        .pay_PoupWrap {
            background: white;
            width: 100%;
            margin: 0 auto;
            border-radius: 10upx;
            flex-direction: column;

            .line1 {
                height: 120upx;
                width: 100%;
                font-size: 30upx;
                color: #000000;
                border-bottom: 1px solid #dddddd;
                align-items: center;
                text {
                    color: #ff1268;
                    font-size: 32upx;
                }
            }
            .line2 {
                width: 100%;
                height: 88upx;
                align-items: center;
                justify-content: space-between;
                font-size: 26upx;
                color: #333333;
                border-bottom: 1px solid #dddddd;
            }
            .btn {
                width: 80%;
                border: 1px solid #dddddd;
                border-radius: 4upx;
                height: 80upx;
                align-items: center;
                justify-content: center;
                margin: 0 auto;
                text {
                    font-size: 28upx;
                    color: #333333;
                    margin-left: 15upx;
                }
            }
            .wachat {
                margin-bottom: 30upx;
                .iconfont {
                    color: #259b24;
                }
            }
            .Alipay {
                margin-bottom: 30upx;
                .iconfont {
                    color: #1296d9;
                }
            }
            .middle {
                flex-direction: column;
                color: #333333;
                font-size: 30upx;
                padding: 30upx 0 50upx;
                justify-content: center;
                .mid-title {
                    color: #333333;
                    font-size: 30upx;
                    font-weight: 600;
                    text-align: center;
                }
                view {
                    color: #ff1268;
                    font-size: 24upx;
                    margin-top: 20upx;
                    justify-content: center;
                    align-items: flex-end;
                    text {
                        font-size: 56upx;
                    }
                    text:last-child {
                        font-size: 24upx;
                        margin-left: 10upx;
                    }
                }
            }
            .choosePayType {
                flex-direction: column;
                width: 100%;
                .btn {
                    height: 80upx;
                }
            }
        }
    }
}
</style>
